import { BASE_URL } from "@/config/base.js";

const pending = []; // 用来记录队列中的请求

// 判断是否有重复的请求并移除
let removePending = (config) => {
  for (let p = 0; p < pending.length; p++) {
    if (pending[p].u === config.url?.split("?")[0] + "&" + config.method) {
      //当当前请求在数组中存在时执行函数体
      pending[p].requestTask.abort();
      pending.splice(p, 1); //数组移除当前请求
    }
  }
};

let show = true;
const request = ({ url, method, params, data, headers }) => {
  return new Promise((resolve, reject) => {
    if (!headers) {
      headers = {
        "content-type": "application/json",
        Authorization: "Bearer " + uni.getStorageSync("token"),
        "Access-Control-Allow-Headers": "appId",
        "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
        "Access-Control-Allow-Origin": "*",
      };
    }
    const options = { url, method, params, data, headers };
    removePending(options);

    // let min = 0;
    // let max = 25;
    // let arrStr = "abcdefghijklmnopqrstuvwxyz";
    // // 0-25随机数
    // let randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
    // let tempUrl = "https://" + arrStr[randomInt] + ".h5.qunxinghuzhu.com";

    // const BASE_URL = tempUrl;

    const requestTask = uni.request({
      // '/dev-api' +
      // url: BASE_URL + "/app/dev-api/" + url,
      // /prod-api
      // url: BASE_URL + "/app" + url,
      url: BASE_URL + "/prod-api/app" + url,
      // url: BASE_URL + '/app' + url,
      data: data,
      method: method,
      header: headers,
      timeout: 20000,
      success: (res) => {
        const { code, msg } = res.data;
        if (code == 200) {
          return resolve(res.data);
        } else if (code == 401) {
          if (show) {
            uni.removeStorageSync("token");
            uni.showModal({
              title: "提示",
              content: "是否登录",
              success: function (res) {
                if (res.confirm) {
                  uni.navigateTo({
                    url: "/pages/login/login",
                  });
                }
              },
            });
            show = false;
            setTimeout(() => {
              show = true;
            }, 3000);
          }
          return;
        }
        uni.showToast({
          icon: "none",
          duration: 3000,
          title: msg ? msg : "系统错误",
        });
        return resolve(res);
      },
      fail(error) {
        // 如果是移除不管
        if (error.errMsg != "request:fail abort") {
          console.log("请求错误：", error);
          uni.showToast({
            icon: "none",
            duration: 3000,
            title: "网络异常，请稍后重试！",
          });
          return resolve(res);
        }
      },
      // 接口调用结束的回调函数（调用成功、失败都会执行）
      complete() {
        // 从请求队列中移除已经执行完成的请求
        const excutingIndex = pending.findIndex(
          (item) => item.requestTask === requestTask
        );
        pending.splice(excutingIndex, 1);
      },
    });
    //把请求加入队列数组中
    pending.push({
      u: options.url?.split("?")[0] + "&" + options.method,
      requestTask: requestTask,
    });
  });
};

// 向外暴露request
export default request;
